package com.mall.web.control.weishang;

import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserLockService;
import com.mall.constant.PropertiesKey;
import com.mall.pojo.UserExtended;
import com.mall.pojo.UserLock;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.MoneyUtil;
import com.tencent.common.Configure;

@Controller
@RequestMapping("/maidian/share/")
public class WeishangShareController {
	
	
	private static final Logger log = LoggerFactory.getLogger(WeishangShareController.class);
	/**
	 * 获取access_token接口地址
	 */
	private static final String ACCESS_TOKEN_API_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	/**
	 * 鉴权请求地址模板
	 */
	private static final String REDIRECT_URL_TPL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";

	@Autowired
	private UserLockService userLockService;
	@Autowired
	private UserExtendedService userExtendedService;

	/**
	 * 用户从分享链接完成交易之后给用户的确认链接
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("index")
	public String index(@RequestParam(required = true) Long mallItemId,@RequestParam(required = true) Long money,HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception{
		log.error("开始授权请求...");
		// 将订单ID先保存在session中，待授权完成后继续取出使用
		log.error("pay>sessionId:{}", request.getSession().getId());
		String state = String.format("%08d", mallItemId);// 这里需要加密
		
		String AUTH_RETURN_URI = PropertiesKey.httpbeginurl+"/weishang/share/confirmSuccess.htm?mallItemId="
				+ mallItemId+"&money="+money;

		String redirectUrl = String.format(REDIRECT_URL_TPL, Configure.getAppid(),
				URLEncoder.encode(AUTH_RETURN_URI, "utf-8"), state);
		log.error("redirectTo:{}", redirectUrl);
		return "redirect:" + redirectUrl;
	}
	@RequestMapping("confirmSuccess")
	public String confirmSuccess(@RequestParam(required = true) Long mallItemId,HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception{
		Double price = Double.parseDouble(request.getParameter("money"));//分销商从该商品中获得的提成
		Long money = MoneyUtil.getDBMoney(price);
		
		Map<String, String[]> params = request.getParameterMap();// 针对get获取get参数
		String[] codes = params.get("code");// 拿到的code的值
		String code = codes[0];// code
		// 获取用户openid
		String authResponse = HttpUtil.sendGet(ACCESS_TOKEN_API_URL,
				String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code", Configure.getAppid(),
						Configure.getAppSecret(), code));
		JSONObject authResponseJson = JSON.parseObject(authResponse);
		log.error("用户authInfo:" + authResponseJson.toString());
		Integer errcode = authResponseJson.getInteger("errcode");
		if (errcode != null && errcode != 0) {
			log.error("请求用户authInfo失败,errcode:{}", errcode);
			return null; // TODO 跳转到error页
		}
		String openId = authResponseJson.getString("openid"); 
		UserLock userLock = this.userLockService.getUserLockByMallItemIdAndOpendIdAndShareUserId(mallItemId, openId,null);
		if (userLock == null) {
			log.error("完成交易用户没有浏览过分销商分享的链接");
			return null;
		}
		
		/**
		 * 进入链接即可分成（或加一个提交填写信息时候分成）
		 */
		Long userId = userLock.getShareUserId();
		if (userId == null ) {
			log.error("分享的链接错误");
			return null;
		}
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(userId);
		if (userExtended == null) {
			log.error("该链接分销商不存在");
			return null;
		}
		userExtended.setBalance(userExtended.getBalance()+money);
		Integer result = this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		if (result == null || result<=0) {
			log.error("分成失败");
		}
		return "weishang/share/confirmSuccess";
	}

}
